package com.thero.core.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by wusk on 2017/11/28.
 * 消息解码工具
 */
public class StreamDecoder extends ByteToMessageDecoder {

    public static final int INTEGER_SIZE = 4;

    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {
        if (buffer.readableBytes() > 2048) {
            buffer.skipBytes(buffer.readableBytes());
        }

        read(buffer, list);
    }

    public void read(ByteBuf buffer, List<Object> list){
        //如果不够一个int长度，不读取
        if(buffer.readableBytes() < INTEGER_SIZE){
            return;
        }
        int readPointer = buffer.readerIndex();
        int length = buffer.readInt();
        //缓冲区长度不够一个消息长度，不读取
        if(buffer.readableBytes() < (length - INTEGER_SIZE)){
            //还原读指针
            buffer.readerIndex(readPointer);
            return;
        }
        MessageHeader header = new MessageHeader();
        header.setLength(buffer.readInt());
        header.setCount(buffer.readShort());
        header.setIndex(buffer.readShort());
        header.setCommand(buffer.readShort());

        byte[] bytes = new byte[length - MessageHeader.HEADER_SIZE];
        buffer.readBytes(bytes);

        ProtocolMessage message = new ProtocolMessage();
        message.setHeader(header);
        message.setMessage(bytes);

        list.add(message);

        read(buffer, list);
    }
}
